package com.bow.demo.module.zookeeper.zkclient;

import org.I0Itec.zkclient.IZkChildListener;
import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.serialize.SerializableSerializer;
import org.apache.zookeeper.CreateMode;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import java.util.List;

/**
 * org.I0Itec.zkclient.ZkClient使用介绍
 * 
 * @author vv
 * @since 2017/8/1.
 */
public class ZkClientDemo {

    private ZkClient zkClient;

    @Before
    public void setup() {
        // zk集群的地址
        String conStr = "127.0.0.1:2181";
        zkClient = new ZkClient(conStr, 10000, 10000, new SerializableSerializer());

    }

    @After
    public void destroy() {
        zkClient.close();
    }

    @Test
    public void crud() {
        String path = "/vv";

        // create
        zkClient.create(path, "vv", CreateMode.PERSISTENT);

        // exists
        boolean result = zkClient.exists(path);
        Assert.assertTrue(result);

        // update data
        zkClient.writeData(path, "vv2");
        String result2 = zkClient.readData(path);
        Assert.assertEquals(result2, "vv2");

        // 清空
        zkClient.deleteRecursive(path);
    }

    @Test
    public void subscribe() {
        String path = "/vv";
        zkClient.create(path, "vv", CreateMode.PERSISTENT);
        zkClient.subscribeChildChanges(path, new ZKChildListener());
        zkClient.subscribeDataChanges(path, new ZKDataListener());
        // 建立一个子节点触发监听
        zkClient.create(path + "/test", null, CreateMode.PERSISTENT_SEQUENTIAL);
        // 修改数据触发监听
        zkClient.writeData(path, "vv3");

        // 清空
        zkClient.deleteRecursive(path);
    }

    /**
     * 监听数据
     */
    private static class ZKDataListener implements IZkDataListener {
        public void handleDataChange(String dataPath, Object data) throws Exception {
            System.out.println(dataPath + " changed :" + data.toString());
        }

        public void handleDataDeleted(String dataPath) throws Exception {
            System.out.println("delete " + dataPath);
        }
    }

    /**
     * 监听子节点
     */
    private static class ZKChildListener implements IZkChildListener {
        /**
         * 用来处理服务器端发送过来的通知
         * 
         * @param parentPath 对应的父节点的路径
         * @param currentChilds 子节点的相对路径
         * @throws Exception e
         */
        public void handleChildChange(String parentPath, List<String> currentChilds) throws Exception {
            System.out.println(parentPath + "'s children changed:");
            System.out.println(currentChilds.toString());
        }
    }
}
